package com.wysiwyg.flow.config.consumer;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.wysiwyg.flow.constants.MessageConstants;
import com.wysiwyg.flow.enums.FlowTag;
import com.wysiwyg.flow.model.dto.FlowMessage;
import com.wysiwyg.flow.service.mq.FlowMessageConsumerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

/**
 * 流程主消费者
 * 统一处理所有流程消息，根据业务标签路由到具体的处理逻辑
 */
@Slf4j
@Service
@RequiredArgsConstructor
@RocketMQMessageListener(
        topic = MessageConstants.FLOW_TOPIC,
        consumerGroup = MessageConstants.FLOW_CONSUMER_GROUP_MAIN
        // 不设置selectorExpression，消费所有消息
)
public class FlowMasterConsumer implements RocketMQListener<String> {

    private final FlowMessageConsumerService flowMessageConsumerService;

    @Override
    public void onMessage(String message) {
        try {
            log.info("接收到流程消息: {}", message);

            // 解析消息
            FlowMessage<?> flowMessage = parseMessage(message);
            FlowTag tag = flowMessage.getTag();

            if (tag == null) {
                log.warn("消息缺少业务标签，跳过处理: {}", message);
                return;
            }

            // 根据业务标签路由到具体的处理方法
            routeByTag(tag, message);

            log.info("流程消息处理完成, tag={}, businessKey={}", tag, flowMessage.getBusinessKey());

        } catch (Exception e) {
            log.error("处理流程消息失败: {}", message, e);
            // TODO: 实现消息重试或死信队列处理
            throw new RuntimeException("消息处理失败", e);
        }
    }

    /**
     * 根据业务标签路由消息
     */
    private void routeByTag(FlowTag tag, String message) {
        switch (tag) {
            case USER_CHANGE:
                flowMessageConsumerService.processUserChange(message);
                break;
            default:
                log.warn("未实现的业务标签处理: {}", tag);
                break;
        }
    }

    /**
     * 解析消息JSON为FlowMessage对象
     */
    private FlowMessage<?> parseMessage(String messageJson) {
        try {
            return JSON.parseObject(messageJson, new TypeReference<FlowMessage<Object>>() {});
        } catch (Exception e) {
            log.error("解析消息失败: {}", messageJson, e);
            throw new RuntimeException("消息格式错误", e);
        }
    }
}
